<template>
  <div class="coding-example">
    <h3>编码组件使用示例</h3>
    
    <el-form ref="form" :model="form" label-width="120px">
      <el-form-item label="产品名称">
        <el-input v-model="form.productName" placeholder="请输入产品名称" />
      </el-form-item>
      
      <el-form-item label="产品编码">
        <CodingInput
          ref="productCodeInput"
          v-model="form.productCode"
          table-name="fun_product"
          field-name="product_code"
          :show-rule-info="true"
          @code-generated="onCodeGenerated"
          @code-confirmed="onCodeConfirmed"
        />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="saveForm" :loading="saving">保存</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import CodingInput from './index.vue'

export default {
  name: 'CodingExample',
  components: {
    CodingInput
  },
  data() {
    return {
      form: {
        productName: '',
        productCode: ''
      },
      saving: false
    }
  },
  methods: {
    // 编码生成回调
    onCodeGenerated(code) {
      console.log('编码已生成（临时）:', code)
    },
    
    // 编码确认回调
    onCodeConfirmed(code) {
      console.log('编码已确认（正式）:', code)
    },
    
    // 保存表单
    async saveForm() {
      this.saving = true
      try {
        // 1. 首先确认编码（这会更新流水号）
        const confirmedCode = await this.$refs.productCodeInput.confirmCurrentCode()
        if (!confirmedCode) {
          this.$message.error('编码确认失败，无法保存')
          return
        }
        
        // 2. 更新表单中的编码
        this.form.productCode = confirmedCode
        
        // 3. 保存表单数据到后端
        console.log('保存表单数据:', this.form)
        
        // 这里调用实际的保存API
        // await saveProduct(this.form)
        
        this.$message.success('保存成功')
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败: ' + (error.message || '未知错误'))
      } finally {
        this.saving = false
      }
    },
    
    // 重置表单
    resetForm() {
      this.form = {
        productName: '',
        productCode: ''
      }
      // 重置编码组件状态
      if (this.$refs.productCodeInput) {
        this.$refs.productCodeInput.currentValue = ''
        this.$refs.productCodeInput.isTemporaryCode = false
        this.$refs.productCodeInput.confirmedCode = null
      }
    }
  }
}
</script>

<style scoped>
.coding-example {
  padding: 20px;
  max-width: 600px;
}
</style>